package com.ruoyi.yys.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Entity;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.yys.common.enums.ErrorStatus;

import java.time.Duration;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 注释
 *
 * @author lys
 * @date 2022/12/26
 */
public class XyUtils {

    /**
     * 获取一个32位的时间id
     *
     * @return {@link String}
     */
    public static String getId32(){
        return DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN) + RandomUtil.randomString(15).toUpperCase(Locale.ROOT);
    }

    /**
     * 列字典转换
     *
     * @param columnDict 样板
     */
    public static List<Entity> dictConvert(Map<String, Map<String, String>> columnDict, List<Entity> datas) {
        if (MapUtil.isEmpty(columnDict)) {
            return datas;
        }
        try {
            if (MapUtil.isNotEmpty(columnDict)) {
                datas = datas.stream().peek(e -> {
                    for (String k : e.keySet()) {
                        if (columnDict.keySet().contains(k)) {
                            //原来的value值
                            String originalV = e.getStr(k);
                            //转换后的value值
                            String v = Convert.toStr(columnDict.get(k).get(originalV), originalV);
                            e.set(k, v);
                        }
                    }
                }).collect(Collectors.toList());
            }
            return datas;
        } catch (Exception e) {
            throw new ServiceException(ErrorStatus.EXCEPTION.getCode(), "列字典转换出错：" + e.getMessage());
        }
    }

    /**
     * 转换时间
     * <=60 {}秒
     * <=60分 {}分{}秒
     * 否则  {}时{}分{}秒
     * @param seconds 秒
     * @return {@link String}
     */
    public static String converTime(Long seconds){
        if(null == seconds){
            return "";
        }
        int constant = 60;
        if(seconds < constant){
            return seconds + "秒";
        }
        Duration duration = Duration.ofSeconds(seconds);
        long minutes = duration.toMinutes();
        long remainingSeconds = duration.minusMinutes(minutes).getSeconds();
        if (minutes < constant) {
            return StrUtil.format("{}分{}秒", minutes, remainingSeconds);
        }
        long hours = minutes / constant;
        minutes = minutes % constant;
        return StrUtil.format("{}时{}分{}秒",hours, minutes, remainingSeconds);
    }
}
